<template>
    <div>
        <Title :title="title"></Title>
        <div ref="right2" style="height: 120px;"></div>
    </div>
</template>
<script>
import { Bar, G2 } from '@antv/g2plot';
import { get } from '@/utils/request';
import moment from 'moment';
import Title from './Title';

export default {
    components: { Title },
    data() {
        return {
            title: '实时pm2.5颗粒物曲线',
            pmData: [],
            barChart: null
        };
    },
    methods: {
        // 初始化基础形状（无任何动画）
        initShape() {
            G2.registerShape('interval', 'normal-interval', {
                draw(cfg, container) {
                    const group = container.addGroup();
                    const path = this.parsePath(this.getRectPath(cfg.points));
                    const { color, style = {}, defaultStyle } = cfg;
                    const fillColor = color || style.fill || defaultStyle.fill;

                    // 仅绘制基础柱状图
                    group.addShape('path', {
                        attrs: { ...style, path, fill: fillColor },
                        name: 'interval'
                    });

                    return group;
                },
                // 基础路径生成方法
                getRectPath(points, isClosed = true) {
                    const path = [];
                    const firstPoint = points[0];
                    path.push(['M', firstPoint.x, firstPoint.y]);
                    for (let i = 1; i < points.length; i++) {
                        path.push(['L', points[i].x, points[i].y]);
                    }
                    if (isClosed) {
                        path.push(['L', firstPoint.x, firstPoint.y]);
                        path.push(['z']);
                    }
                    return path;
                }
            });
        },

        loadLine() {
            if (!this.$refs.right2 || !this.pmData.length) return;

            // 销毁已有实例
            if (this.barChart) {
                this.barChart.destroy();
            }

            // 初始化基础形状（无动画）
            this.initShape();

            // 处理图表数据
            const chartData = this.pmData.map(item => ({
                time: item.insert_time,
                type: 'PM2.5',
                value: Number(item.pm25)
            }));

            // 创建柱状图（完全关闭动画）
            this.barChart = new Bar(this.$refs.right2, {
                data: chartData,
                xField: 'value',
                yField: 'time',
                seriesField: 'type',
                padding: [10, 40, 30, 50],
                legend: false,
                label: {
                    position: 'right',
                    formatter: (datum) => `${datum.value}`,
                    style: { fill: 'white' }, // PM数值设为白色
                    animate: false // 关闭标签动画
                },
                shape: 'normal-interval', // 使用无动画形状
                yAxis: { label: { style: { fill: 'white' } } },
                xAxis: { label: { style: { fill: 'white' } } },
                barStyle: { 
                    fillOpacity: 0.9,
                    fill: '#722ED1'
                },
                animation: false, // 完全关闭图表动画
                tooltip: {
                    showMarkers: false,
                    domStyles: {
                        "g2-tooltip": {
                            background: "#147",
                            color: 'white',
                            fontSize: 12
                        },
                        "g2-tooltip-list-item": {
                            paddingLeft: '16px'
                        }
                    },
                    formatter: (datum) => ({
                        name: datum.time,
                        value: [`PM2.5：${datum.value}`]
                    })
                },
                interactions: [] // 移除所有交互
            });

            this.barChart.render();
        },

        async getPmData() {
            try {
                const res = await get('/dashboard/pageQueryTodayData', { page: 1, pageSize: 100 });
                if (!res?.data?.list?.length) {
                    this.pmData = [];
                    return;
                }
                this.pmData = res.data.list
                   .filter((_, index) => index % 20 === 0)
                   .map(item => ({
                        insert_time: moment(item.insert_time).format('HH:mm'),
                        pm25: item.pm25 || 0
                    }));
            } catch (error) {
                console.error('获取PM2.5数据失败:', error);
                this.pmData = Array.from({ length: 6 }, (_, i) => ({
                    insert_time: `${(8 + i).toString().padStart(2, '0')}:00`,
                    pm25: 30 + Math.floor(Math.random() * 50)
                }));
            }
        }
    },
    async mounted() {
        await this.getPmData();
        this.loadLine();
    },
    beforeDestroy() {
        if (this.barChart) {
            this.barChart.destroy();
        }
    }
};
</script>
<style scoped>
::v-deep.g2-tooltip {
    background: #147!important;
    color: white!important;
}
::v-deep.g2-tooltip-list {
    margin: 0!important;
    padding: 0!important;
    list-style: none!important;
}
::v-deep.g2-tooltip-list-item {
    padding-left: 16px!important;
}
/* 确保标签文字为白色 */
::v-deep.g2-label {
    fill: white!important;
}
</style>